#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#pragma warning(disable:4996)
#define MAX_CONTACTS 200

typedef struct {
	char name[50];
	char number[20];
}Contact;

Contact contacts[MAX_CONTACTS];
int contactsum = 0;

void enter() {
	char choice;
	if (contactsum == 0) {
		printf("无联系人，是否输入?(y/n)");
		scanf(" %c", &choice);
		if (choice != 'y' && choice != 'Y') {
			return;
		}
	}
	printf("请输入姓名:");
	scanf("%s", contacts[contactsum].name);
	printf("请输入号码:");
	scanf("%s", contacts[contactsum].number);
	contactsum++;
	printf("联系人已录入\n");
}

void del() {
	char namedelete[50];
	printf("请输入要删除的联系人姓名:");
	scanf("%s", &namedelete);
	int i, n = 0;
	for (i = 0; i < contactsum; i++) {
		if (strcmp(contacts[i].name, namedelete) == 0) {
			n = 1;
			for (; i < contactsum - 1; i++) {
				contacts[i] = contacts[i + 1];
			}
			contactsum--;
			printf("联系人已删除"); break;
		}
	}
	if (!n) {
		printf("不存在该联系人\n");
	}
}

void list() {
	if (contactsum == 0) {
		printf("无联系人\n");
	}
	else {
		printf("联系人:\n");
		for (int i = 0; i < contactsum; i++) {
			printf("%s:%s\n", contacts[i].name, contacts[i].number);
		}
	}
}

void search() {
	char namesearch[50];
	printf("输入联系人姓名:");
	scanf("%s", &namesearch);
	int i, n = 0;
	for (i = 0; i < contactsum; i++) {
		if (strcmp(contacts[i].name, namesearch) == 0) {
			n = 1;
			printf("%s:%s", contacts[i].name, contacts[i].number);
			break;
		}
	}
	if (!n) {
		printf("无该联系人\n");
	}
}

void save() {
	FILE* file = fopen("contacts.txt", "w");
	if (file == NULL) {
		printf("无法打开文件进行保存\n");
		return;
	}
	for (int i = 0; i < contactsum; i++) {
		fprintf(file, "%s %s\n", contacts[i].name, contacts[i].number);
	}
	fclose(file);
	printf("Saving file\n");
}

void load() {
	FILE* file = fopen("contacts.txt", "r");
	if (file == NULL) {
		printf("无法打开文件进行加载\n");
		return;
	}
	contactsum = 0;
	while (fscanf(file, "%s %s", contacts[contactsum].name, contacts[contactsum].number) != EOF) {
		contactsum++;
	}
	fclose(file);
	printf("数据已加载成功\n");
}

int main() {
	int choice;
	while (1) {
		printf("\n通讯录管理系统\n");
		printf("1.通讯录录入信息\n");
		printf("2.通讯录删除信息\n");
		printf("3.通讯录显示\n");
		printf("4.通讯录查询\n");
		printf("5.保存通讯录信息\n");
		printf("6.数据加载\n");
		printf("7.推出通讯录系统\n");
		printf("请输入你的选择：");
		scanf("%d", &choice);
		switch (choice) {
		case 1:enter(); break;
		case 2:del(); break;
		case 3:list(); break;
		case 4:search(); break;
		case 5:save(); break;
		case 6:load(); break;
		case 7:
			printf("已退出通讯录系统\n"); break;
		default:printf("无效选择，请重新输入\n");
		}
	}
	while (choice != 7);
	return 0;
}